package com.yimaxiaoerlang.imdemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.yimaxiaoerlang.im_core.core.YMIMClient;
import com.yimaxiaoerlang.im_core.core.other.YMResultCallback;
import com.yimaxiaoerlang.im_core.model.YMContacts;
import com.yimaxiaoerlang.im_core.model.YMGroupEntity;
import com.yimaxiaoerlang.im_core.model.YMRoomEntity;
import com.yimaxiaoerlang.im_core.model.conversation.YMConversation;
import com.yimaxiaoerlang.im_kit.ui.AddFriendActivity;
import com.yimaxiaoerlang.im_kit.ui.ChatActivity;
import com.yimaxiaoerlang.im_kit.ui.ChatRoomFragment;
import com.yimaxiaoerlang.im_kit.ui.ChatRoomListActivity;
import com.yimaxiaoerlang.im_kit.ui.ContactsFragment;
import com.yimaxiaoerlang.im_kit.ui.ConversationListFragment;
import com.yimaxiaoerlang.im_kit.ui.MainMeFragment;
import com.yimaxiaoerlang.im_kit.ui.SearchUserActivity;
import com.yimaxiaoerlang.im_kit.ui.SelectFriendActivity;
import com.yimaxiaoerlang.im_kit.utils.SystemBarHelper;
import com.yimaxiaoerlang.im_kit.utils.UserUtils;
import com.yimaxiaoerlang.im_kit.view.actionbar.menu.Menu;
import com.yimaxiaoerlang.im_kit.view.actionbar.menu.PopActionClickListener;
import com.yimaxiaoerlang.im_kit.view.actionbar.menu.PopMenuAction;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private ArrayList<Fragment> mFragments = new ArrayList<>();
    private String[] mTitles = {"首页", "联系人", "聊天室", "设置"};
    private int[] mIconUnselectIds = {
            R.mipmap.tab_home_unselect,
            R.mipmap.tab_contact_unselect,
            R.mipmap.tab_speech_unselect,
            R.mipmap.tab_more_unselect};
    private int[] mIconSelectIds = {
            R.mipmap.tab_home_select,
            R.mipmap.tab_contact_select,
            R.mipmap.tab_speech_select,
            R.mipmap.tab_more_select};
    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private View titleBar;
    private Menu menu;
    private ImageButton btnMore;
    private RelativeLayout btnSearch;
    private TextView tvTitle;
    private boolean isChatroom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initTitleBar();
        initTabLayout();
    }

    private void initTitleBar() {
        titleBar = findViewById(R.id.index_title);
        btnMore = findViewById(com.yimaxiaoerlang.im_kit.R.id.btn_more);
        btnSearch = findViewById(com.yimaxiaoerlang.im_kit.R.id.btn_search);
        tvTitle = findViewById(com.yimaxiaoerlang.im_kit.R.id.tv_title);
        SystemBarHelper.setStatusBarDarkMode(this);
        SystemBarHelper.immersiveStatusBar(this, 0f);
        SystemBarHelper.setPadding(this, titleBar);
        findViewById(com.yimaxiaoerlang.im_kit.R.id.btn_more).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (menu == null) {
                    return;
                }
                if (menu.isShowing()) {
                    menu.hide();
                } else {
                    menu.show();
                }
            }
        });
    }

    private void initTabLayout() {
        mFragments.add(new ConversationListFragment());
        mFragments.add(new ContactsFragment());
        mFragments.add(new ChatRoomFragment());
        mFragments.add(new MainMeFragment());
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }

        CommonTabLayout tabLayout = findViewById(R.id.tab_layout);
        tabLayout.setTabData(mTabEntities, this, R.id.container, mFragments);
        tabLayout.setCurrentTab(0);
        setConversationMenu(false);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                setConversationMenu(position == 2);
                btnMore.setVisibility(position == 3 ? View.GONE : View.VISIBLE);
                tvTitle.setText(mTitles[position]);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }

    private void setConversationMenu(boolean isChatroom) {
        this.isChatroom = isChatroom;
        menu = new Menu(this, btnMore);
        PopActionClickListener popActionClickListener = new PopActionClickListener() {
            @Override
            public void onActionClick(int position, Object data) {
                PopMenuAction action = (PopMenuAction) data;
                if (TextUtils.equals(action.getActionName(), getResources().getString(com.yimaxiaoerlang.im_kit.R.string.start_conversation))) {
                    SelectFriendActivity.start(MainActivity.this, false);
                }

                if (TextUtils.equals(action.getActionName(), getResources().getString(com.yimaxiaoerlang.im_kit.R.string.add_user_friend))) {
                    SearchUserActivity.start(MainActivity.this);
                }

                if (TextUtils.equals(action.getActionName(), getResources().getString(com.yimaxiaoerlang.im_kit.R.string.create_group_chat))) {
                    SelectFriendActivity.start(MainActivity.this, true);
                }

                if (TextUtils.equals(action.getActionName(), getResources().getString(com.yimaxiaoerlang.im_kit.R.string.create_chat_room))) {
                    SelectFriendActivity.start(MainActivity.this, true);
                }

                if (TextUtils.equals(action.getActionName(), getResources().getString(com.yimaxiaoerlang.im_kit.R.string.search_chat_room))) {
                    ChatRoomListActivity.start(MainActivity.this);
                }

                menu.hide();
            }
        };

        // 设置右上角+号显示PopAction
        List<PopMenuAction> menuActions = new ArrayList<>();

        PopMenuAction action = new PopMenuAction();

        action.setActionName(getResources().getString(com.yimaxiaoerlang.im_kit.R.string.start_conversation));
        action.setActionClickListener(popActionClickListener);
        action.setIconResId(com.yimaxiaoerlang.im_kit.R.mipmap.create_c2c);
        menuActions.add(action);

        action = new PopMenuAction();
        action.setActionName(getResources().getString(com.yimaxiaoerlang.im_kit.R.string.add_user_friend));
        action.setActionClickListener(popActionClickListener);
        action.setIconResId(com.yimaxiaoerlang.im_kit.R.mipmap.create_c2c);
        menuActions.add(action);

        action = new PopMenuAction();
        action.setActionName(getResources().getString(com.yimaxiaoerlang.im_kit.R.string.create_group_chat));
        action.setIconResId(com.yimaxiaoerlang.im_kit.R.mipmap.group_icon);
        action.setActionClickListener(popActionClickListener);
        menuActions.add(action);

        if (isChatroom) {
            menuActions.clear();
            action = new PopMenuAction();
            action.setActionName(getResources().getString(com.yimaxiaoerlang.im_kit.R.string.create_chat_room));
            action.setIconResId(com.yimaxiaoerlang.im_kit.R.mipmap.group_icon);
            action.setActionClickListener(popActionClickListener);
            menuActions.add(action);
            action = new PopMenuAction();
            action.setActionName(getResources().getString(com.yimaxiaoerlang.im_kit.R.string.search_chat_room));
            action.setIconResId(com.yimaxiaoerlang.im_kit.R.mipmap.group_icon);
            action.setActionClickListener(popActionClickListener);
            menuActions.add(action);
        }

        menu.setMenuAction(menuActions);
    }

    private void startChatActivity(String tid, String title) {
        YMConversation conversation = new YMConversation();
        conversation.setTargetId(tid);
        conversation.setConversationType(YMConversation.ConversationType.PRIVATE);
        conversation.setConversationTitle(title);
        Intent intent = new Intent(MainActivity.this, ChatActivity.class);
        intent.putExtra("conversation", conversation);
        startActivity(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null && resultCode == Activity.RESULT_OK) {
            if (requestCode == SelectFriendActivity.SELECT_FRIEND_REQ) {
                List<YMContacts> selectList = (ArrayList<YMContacts>) data.getSerializableExtra(SelectFriendActivity.SELECT_FRIEND_RESULT);
                if (selectList.size() == 1) {
                    // 创建会话
                    YMContacts contacts = selectList.get(0);
                    startChatActivity(contacts.getTid(), contacts.getUsername());
                } else {
                    // 创建群聊
                    List<YMContacts> groupList = new ArrayList<>();
                    YMContacts lord = new YMContacts();
                    lord.setUserAvatar(UserUtils.getInstance().getUser().getUserAvatar());
                    lord.setUsername(UserUtils.getInstance().getUser().getUsername());
                    lord.setTid(UserUtils.getInstance().getUser().getUid());
                    groupList.add(lord);
                    groupList.addAll(selectList);
                    List<String> idsList = new ArrayList<>();
                    StringBuffer nameSb = new StringBuffer();
                    for (int i = 0; i < groupList.size(); i++) {
                        if (i > 0) {
                            nameSb.append(",");
                        }
                        idsList.add(groupList.get(i).getTid() + "");
                        nameSb.append(groupList.get(i).getUsername());
                    }
                    if (isChatroom) {
                        YMIMClient.roomManager().createRoomWithName(nameSb.toString() + "的聊天室", UserUtils.getInstance().getUser().getUserAvatar(), idsList, new YMResultCallback<YMRoomEntity>() {
                            @Override
                            public void onSuccess(YMRoomEntity group) {

                            }

                            @Override
                            public void onError(int errorCode) {

                            }
                        });
                    } else {
                        YMIMClient.groupManager().createGroupWithName(nameSb.toString() + "的群聊", UserUtils.getInstance().getUser().getUserAvatar(), idsList, new YMResultCallback<YMGroupEntity>() {
                            @Override
                            public void onSuccess(YMGroupEntity group) {

                            }

                            @Override
                            public void onError(int errorCode) {

                            }
                        });
                    }
                }
            } else if (requestCode == SearchUserActivity.SEARCH_FRIEND_REQ) {
                // 搜索添加好友
                YMContacts contacts = (YMContacts) data.getSerializableExtra(SearchUserActivity.SEARCH_FRIEND_RESULT);
                AddFriendActivity.start(MainActivity.this, contacts.getUsername(), contacts.getTid(), contacts.getUserAvatar());
            }
        }
    }

    class TabEntity implements CustomTabEntity {
        public String title;
        public int selectedIcon;
        public int unSelectedIcon;

        public TabEntity(String title, int selectedIcon, int unSelectedIcon) {
            this.title = title;
            this.selectedIcon = selectedIcon;
            this.unSelectedIcon = unSelectedIcon;
        }

        @Override
        public String getTabTitle() {
            return title;
        }

        @Override
        public int getTabSelectedIcon() {
            return selectedIcon;
        }

        @Override
        public int getTabUnselectedIcon() {
            return unSelectedIcon;
        }
    }
}